# consistency_check.py - 数据一致性检查工具
import logging
from db_pool import get_db_connection
from config import Config
from script_storage import script_storage
from metadata_storage import metadata_storage

logger = logging.getLogger('consistency_check')


def check_data_consistency():
    """检查数据一致性并修复"""
    logger.info("Starting data consistency check...")

    # 加载元数据
    api_metadata, error = metadata_storage.load_metadata()
    if error:
        logger.error(f"Failed to load metadata: {error}")
        return False, f"Failed to load metadata: {error}"

    # 检查每个API的脚本是否存在
    inconsistent_apis = []
    for api_id in list(api_metadata.keys()):
        if not script_storage.script_exists(api_id):
            logger.warning(f"Script missing for API {api_id}, removing from metadata")
            inconsistent_apis.append(api_id)

    # 移除不一致的API
    for api_id in inconsistent_apis:
        del api_metadata[api_id]

    if inconsistent_apis:
        # 保存修复后的元数据
        success, error = metadata_storage.save_metadata(api_metadata)
        if success:
            logger.info(f"Fixed {len(inconsistent_apis)} inconsistent APIs")
        else:
            logger.error(f"Failed to save fixed metadata: {error}")
            return False, f"Failed to save fixed metadata: {error}"

    logger.info("Data consistency check completed")
    return True, f"Found and fixed {len(inconsistent_apis)} inconsistent APIs"


def cleanup_orphaned_scripts():
    """清理孤儿脚本（有脚本但没有元数据的）"""
    logger.info("Cleaning up orphaned scripts...")

    # 获取所有脚本ID
    connection = None
    try:
        connection = get_db_connection()
        cursor = connection.cursor()
        cursor.execute(f"SELECT api_id FROM {Config.SCRIPTS_TABLE}")
        script_api_ids = {row['api_id'] for row in cursor.fetchall()}
    except Exception as e:
        logger.error(f"Failed to get script IDs: {str(e)}")
        return False, f"Failed to get script IDs: {str(e)}"
    finally:
        if connection:
            connection.close()

    # 加载元数据
    api_metadata, error = metadata_storage.load_metadata()
    if error:
        logger.error(f"Failed to load metadata: {error}")
        return False, f"Failed to load metadata: {error}"

    metadata_api_ids = set(api_metadata.keys())

    # 找到孤儿脚本
    orphaned_api_ids = script_api_ids - metadata_api_ids

    # 删除孤儿脚本
    for api_id in orphaned_api_ids:
        success, error = script_storage.delete_script(api_id)
        if success:
            logger.info(f"Deleted orphaned script for API: {api_id}")
        else:
            logger.error(f"Failed to delete orphaned script for API {api_id}: {error}")

    logger.info(f"Cleaned up {len(orphaned_api_ids)} orphaned scripts")
    return True, f"Cleaned up {len(orphaned_api_ids)} orphaned scripts"